<meta charset='utf-8'>
<meta name='viewport' content='width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0'>
<style>
        #info {
                color: #fff;
                position: absolute;
                bottom: 10px;
                width: 100%;
                text-align: center;
                z-index: 100;
                display:block;
                
        }
</style>
<body style='font-family: Monospace; background-color: #000000; margin: 0px; overflow: hidden'>
<div style='color: #fff; position: absolute; bottom: 10px; width: 100%; text-align: center; z-index: 100; display:block;'>
        basic example for chromium-tango
</div>


<!-- include three.js dependancy -->
<script src='vendor/three.js/build/three.js'></script>
<script src='vendor/three.js/examples/js/controls/VRControls.js'></script>
<script src='vendor/three.js/examples/js/libs/stats.min.js'></script>
<script src='vendor/three.js/examples/js/libs/dat.gui.min.js'></script>

<script src='../vendor/chromium-tango/THREE.WebAR.js'></script>
        
<script>
	// array of functions for the rendering loop
	var onRenderFcts= [];

        var parameters = {
                showSeeThroughCamera : true,
                continuousPicking : false,
                showPointCloud : true,
                pointsToSkip : 0,    
        }

        //////////////////////////////////////////////////////////////////////////////
        //                setup three.js
        //////////////////////////////////////////////////////////////////////////////

        // Create the renderer
        var renderer = new THREE.WebGLRenderer()
        renderer.autoClear = false;
        renderer.setPixelRatio( window.devicePixelRatio )
        renderer.setSize( window.innerWidth, window.innerHeight )
        document.body.appendChild( renderer.domElement )

        // Create the 3D scene and camera
        var scene = new THREE.Scene()
        
        // init camera
        var camera = new THREE.PerspectiveCamera( 42, window.innerWidth / window.innerHeight, 0.01, 20 )
        var controls = new THREE.VRControls(camera)
        onRenderFcts.push(function(){
                controls.update()
        })

        // Add some lighting
        var directionalLight = new THREE.DirectionalLight( 0xffffff)
        directionalLight.position.set( 1, 1, 1)
        scene.add( directionalLight )

        // handle window resize
        window.addEventListener( 'resize', function onWindowResize() {
                if (vrDisplay)  THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay, camera)
                renderer.setSize( window.innerWidth, window.innerHeight )
        }, false )

        //////////////////////////////////////////////////////////////////////////////
        //                handle videoPlane 
        //////////////////////////////////////////////////////////////////////////////

        // Create the see through camera scene and camera
        var sceneOrtho = new THREE.Scene()
        var cameraOrtho = new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 100 )


        //////////////////////////////////////////////////////////////////////////////
        //                create model
        //////////////////////////////////////////////////////////////////////////////

        var MODEL_SIZE_IN_METERS = 0.1;

        // Create a cube model of 10 cm size.
        var geometry = new THREE.ConeBufferGeometry( MODEL_SIZE_IN_METERS / 2, MODEL_SIZE_IN_METERS)
        var material = new THREE.MeshLambertMaterial({
                color: 'orange'
        })
        var model = new THREE.Mesh(geometry, material)
        // Apply a rotation to the model so it faces in the direction of the
        // normal of the plane when the picking based reorientation is done
        model.geometry.rotateZ(THREE.Math.degToRad(-90))
        model.position.set(0, 0, -2)
        scene.add(model)
        
        //////////////////////////////////////////////////////////////////////////////
        //                add stats
        //////////////////////////////////////////////////////////////////////////////
        // Create a way to measure performance
        var stats = new Stats()
        document.body.appendChild( stats.dom )
        onRenderFcts.push(function(){
                stats.update()
        })
        //////////////////////////////////////////////////////////////////////////////
        //                add gui
        //////////////////////////////////////////////////////////////////////////////

        // Initialize the dat.GUI.
        var datGUI = new dat.GUI()
        datGUI.add(parameters, 'showSeeThroughCamera').name('Show seethrough camera')
        datGUI.add(parameters, 'continuousPicking').name('Continuous picking')
        datGUI.add(parameters, 'pointsToSkip', 0, 10).name('Points to skip')
                
        //////////////////////////////////////////////////////////////////////////////
        //                vrDisplay
        //////////////////////////////////////////////////////////////////////////////
                
        
        // WebAR is currently based on the WebVR API so try to find the right VRDisplay instance.
        if( navigator.getVRDisplays === undefined ){
                alert('No navigator.getVRDisplays. PANIC!!')
        }

        var vrDisplay = null
        navigator.getVRDisplays().then(function(vrDisplays){
                for( var i = 0; i < vrDisplays.length; i++ ){
                        if( vrDisplays[i].displayName === 'Tango VR Device' ){
                                vrDisplay = vrDisplays[i];
                                break;
                        }
                }
                if( vrDisplay === null ){
                        console.warn('No Tango WebAR VRDisplay found. Falling back to a video.')
                }
                initVrDisplay(vrDisplay)
        })

        function initVrDisplay(vrDisplay){
                console.assert(vrDisplay)
                // make camera fit vrDisplay
                THREE.WebAR.resizeVRSeeThroughCamera(vrDisplay, camera)

                // init videoPlane
                var videoPlane = THREE.WebAR.createVRSeeThroughCameraMesh(vrDisplay)
                sceneOrtho.add(videoPlane)
                onRenderFcts.push(function(){
                        // Make sure that the camera is correctly displayed depending on the
                        // device and camera orientations.
                        THREE.WebAR.updateCameraMeshOrientation(vrDisplay, videoPlane)                        
                })

                //////////////////////////////////////////////////////////////////////////////
                //                Handle point cloud
                //////////////////////////////////////////////////////////////////////////////
                var material = new THREE.PointsMaterial({
                        size: 0.01, 
                        vertexColors: THREE.VertexColors
                })
                material.depthWrite = false;
                
                var vrPointCloud = new THREE.WebAR.VRPointCloud(vrDisplay, true)
                var geometry = vrPointCloud.getBufferGeometry()

                var pointsObject = new THREE.Points(geometry, material)
                // Points are changing all the time so calculating the frustum culling volume is not very convenient.
                pointsObject.frustumCulled = false;
                pointsObject.renderDepth = 0;
                if( parameters.showPointCloud === true )   scene.add(pointsObject)
                
                onRenderFcts.push(function(){
                        // Update the point cloud. Only if the point cloud will be shown the
                        // geometry is also updated.
                        vrPointCloud.update(parameters.showPointCloud, parameters.pointsToSkip, true)                        
                })
                // handle datGUI
                datGUI.add(parameters, 'showPointCloud').onFinishChange(function(value) {
                        if( value )     scene.add(pointsObject)
                        else            scene.remove(pointsObject)
                }).name('Show Point Cloud')
        }

                        
        //////////////////////////////////////////////////////////////////////////////
        //                picking
        //////////////////////////////////////////////////////////////////////////////

        // Wherever the user clicks in the screen, place the model.
        var mousePosition = new THREE.Vector3()
        renderer.domElement.addEventListener('click', function(event) {
                // set mousePosition
                mousePosition.x = event.pageX / window.innerWidth;
                mousePosition.y = event.pageY / window.innerHeight;
                // picking
                picking()
        })
        
        onRenderFcts.push(function(){
                // If continuous picking is enabled, use the center of the screen to continuously pick.
                if (parameters.continuousPicking === false) return

                // set mousePosition in the middle of the screen
                mousePosition.x = 0.5;
                mousePosition.y = 0.5;
                // do a picking now
                picking()
        })

        function picking() {
                if (vrDisplay === null ) return

                var pointAndPlane = vrDisplay.getPickingPointAndPlaneInPointCloud(mousePosition.x, mousePosition.y)
                if( pointAndPlane == null ) {
                        console.warn('Could not retrieve the correct point and plane.')
                        return
                }

                // Orient and position the model in the picking point according
                // to the picking plane. The offset is half of the model size.
                THREE.WebAR.positionAndRotateObject3DWithPickingPointAndPlaneInPointCloud(
                        pointAndPlane, model, MODEL_SIZE_IN_METERS / 2
                )
        }

        //////////////////////////////////////////////////////////////////////////////
        //                Code Separator
        //////////////////////////////////////////////////////////////////////////////
        onRenderFcts.push(function(){
                // Render the see through camera scene
                renderer.clear()
                
                if (parameters.showSeeThroughCamera){                                
                        renderer.render( sceneOrtho, cameraOrtho )
                        // Render the perspective scene
                        renderer.clearDepth()
                }
                
                
                renderer.render( scene, camera )                        
        })

        //////////////////////////////////////////////////////////////////////////////
        //                rendering loop
        //////////////////////////////////////////////////////////////////////////////       
	// run the rendering loop
	var lastTimeMsec= null
	requestAnimationFrame(function animate(nowMsec){
		// keep looping
		requestAnimationFrame( animate )
		// measure time
		lastTimeMsec	= lastTimeMsec || nowMsec-1000/60
		var deltaMsec	= Math.min(200, nowMsec - lastTimeMsec)
		lastTimeMsec	= nowMsec
		// call each update function
		onRenderFcts.forEach(function(onRenderFct){
			onRenderFct(deltaMsec/1000, nowMsec/1000)
		})
	})
</script></body>
